// 引入接口文件
import {
  deleteFun,
  queryAllAddress,importExcel
} from './soilFilmMarketServ.js'
import { message } from 'antd'
import {cloneDeep} from 'lodash'
import { makeAddress } from "utils/util"
import config from 'config/config'
import axios from 'axios'
import $ from 'jquery'
import { rstr2b64 } from '../../../../utils/md5'
const defultState = {
    biz:{
      queryForm: {}
    },
    projectList: [],
    areaList: [],
}

const tmpModule = {
  state: cloneDeep(defultState),
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        if('' + tmpModule.pathname === '' + pathname){
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          dispatch({type: 'findProduct',payload: {}})
          dispatch({ type: 'getAreaList', payload: {} });
        }
      })
    },
  },


  effects: {
    *getAreaList({ payload }, { put, call, select }) {
        const data = yield call(queryAllAddress, {})
        //todo data.success //接口格式需要调整
        if (data.success) {
            let list = []
            let areaList = []
            let arr = [data.data[0]]
            let attr = [data.data[data.data.length - 1]]
            data.data[0] = {
                label: "北京",
                value: "110100",
                children: arr
            }
            data.data[data.data.length - 1] = {
                label: "澳门",
                value: "820000",
                children: attr
            }
            //去掉第三级，
            list = makeAddress(data.data, 2)
            for(var item of list){
              if(item.children){
                for(var itemed of item.children){
                  itemed.value = itemed.label
                  areaList.push(itemed)
                }
              }
            }
            yield put({ type: 'updateStore', payload: { areaList } });
        }
    },
    *deleteFun({payload},{put,select,call}){
      let params = {
        id: payload.id,
      }
      const { success, msg, data } = yield call(deleteFun, {...params})
      let defultState = yield select(state => state[tmpModule.namespace])
      if(success){
        message.success('操作成功')
        defultState.biz.refreshListDatas(true)
      }
    },
    *upload({payload},{put,select,call}){
        let file =  payload.files[0]
        let fileSize = (file.size) / 1024
        if (fileSize > 1024 * 20) {
            message.warn('文件大小不得超过 20M')
          return
        }
        let fileNameType = file.name.split('.').pop();
        let fileType = ['xlsx','xls']
        if (fileType.indexOf(fileNameType) < 0) {
            message.warn('文件格式必须为 xlsx 、xls')
          return
        }
        let fileInfo = new FormData()
        if (file) {
          fileInfo.append('file', file)
        }
        let params = {
          userId: localStorage.getItem('username'),
          file:fileInfo
        }
        let { success,value,hotValue} = yield call(importExcel, params)
        let defultState = yield select(state => state[tmpModule.namespace])
        $("#file").val(null);
        if(success){
          message.success('导入成功')
          defultState.biz.refreshListDatas(true)
        }
    },
    *getExcel({payload},{put,select,call}){
      axios({
          method: 'post',
          url:`${config.aheadPlan}admin/landAuction/landAuction/getExcel`,
          responseType: 'blob',
          headers: {
            "X-Pc-Token":localStorage.getItem("username")+','+new Date().getTime()+','+rstr2b64(localStorage.getItem("username")+','+new Date().getTime())
          },
          data: {},
      }).then(res => {
          const content = res.data
          const blob = new Blob([content])
          Date.prototype.Format = function (fmt) { // author: meizz
              var o = {
                  "M+": this.getMonth() + 1, // 月份
                  "d+": this.getDate(), // 日
                  "h+": this.getHours(), // 小时
                  "m+": this.getMinutes(), // 分
                  "s+": this.getSeconds(), // 秒
                  "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
                  "S": this.getMilliseconds() // 毫秒
              };
              if (/(y+)/.test(fmt))
                  fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
              for (var k in o)
                  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                      return fmt;
          }
          let dateTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
          let fileName = `土拍市场导入模板 ${dateTime}.xls`
          if ('download' in document.createElement('a')) { // 非IE下载
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else { // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
          message.success('导出成功')
      })
    },
    *exportExcel({payload},{put,select,call}){
      let {biz} = yield select(state => state[tmpModule.namespace])
      let tempParams = {...biz.queryForm}
      let tempurl = `${config.aheadPlan}admin/landAuction/landAuction/exportXls`
      axios({
          method: 'post',
          url:tempurl,
          responseType: 'blob',
          headers: {
            "X-Pc-Token":localStorage.getItem("username")+','+new Date().getTime()+','+rstr2b64(localStorage.getItem("username")+','+new Date().getTime())
          },
          data: tempParams,
      }).then(res => {
          const content = res.data
          const blob = new Blob([content])
          Date.prototype.Format = function (fmt) { // author: meizz
              var o = {
                  "M+": this.getMonth() + 1, // 月份
                  "d+": this.getDate(), // 日
                  "h+": this.getHours(), // 小时
                  "m+": this.getMinutes(), // 分
                  "s+": this.getSeconds(), // 秒
                  "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
                  "S": this.getMilliseconds() // 毫秒
              };
              if (/(y+)/.test(fmt))
                  fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
              for (var k in o)
                  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                      return fmt;
          }
          let dateTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
          let fileName = `土拍市场导出 ${dateTime}.xls`
          if ('download' in document.createElement('a')) { // 非IE下载
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else { // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
          message.success('导出成功')
      })
    },
  },
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
